<template>
  <div class="container">
    <Breadcrumb :items="['数据分析',  '政府服务数据情况']" />
    <a-card class="general-card" style="padding-top:5px">
      <a-row>
      <a-col :flex="1">
        <a-form :model="formModel" label-align="right">
          <a-row :gutter="16">
            <a-space direction="horizontal" :size="5">
              <a-form-item field="areaName" label-col-flex="80px" label="统计县市区">
                <a-select v-model="formModel.areaName.value" :style="{ width: '150px' }" allow-clear
                placeholder="全部"
                  :trigger-props="{ autoFitPopupMinWidth: true }">
                  <a-option value="市本级">市本级</a-option>
                  <a-option value="黄州区">黄州区</a-option>
                  <a-option value="团风县">团风县</a-option>
                  <a-option value="红安县">红安县</a-option>
                  <a-option value="麻城市">麻城市</a-option>
                  <a-option value="罗田县">罗田县</a-option>
                  <a-option value="英山县">英山县</a-option>
                  <a-option value="浠水县">浠水县</a-option>
                  <a-option value="蕲春县">蕲春县</a-option>
                  <a-option value="武穴市">武穴市</a-option>
                  <a-option value="黄梅县">黄梅县</a-option>
                </a-select>
              </a-form-item>
              <a-form-item field="quarter" label-col-flex="80px"
                label="时间范围">
                <a-range-picker
                  v-model="formModel.dateRange.value"
                  mode="date"
                  style="width: 254px;"
                />
              </a-form-item>
                <a-form-item field="quarter" label-col-flex="100px"
                  label="统计截止日期">
                  <a-input
                    v-model="formModel.endTime.value"
                    readonly
                    disabled
                    style="width: 150px;"
                  />
                </a-form-item>
              <a-form-item label-col-flex="0px" label="">
                <a-space direction="horizontal" :size="12">
                  <a-button @click="fetchData">
                    <template #icon>
                      <icon-search />
                    </template>
                    查询
                  </a-button>
                </a-space>
              </a-form-item>
            </a-space>
          </a-row>
        </a-form>
      </a-col>
    </a-row>
    <a-table :data="renderData" :columns="columns" sticky-header :pagination="false" page-position="bl" :summary-span-method="spanMethod" :bordered="{cell:true}" :summary="summary" :scrollbar="true"
      :scroll="{ x: '4700px', y: '700px' }">
      <template #summary-cell="{ column, record, rowIndex }">
        <span>{{ record[column.dataIndex] }}</span>
      </template>
    </a-table> 
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { Modal, Message } from '@arco-design/web-vue';
import { postRequest, uploadFileRequest } from '@/api/common';
import { formatSortByGov,formatSortByTitle } from '@/utils/sortUtil';
import { baseURL } from '@/api/base';
import { isNumber } from 'lodash';
const router = useRouter();
const formModel = {
  areaName: ref(""),
  dateRange: ref<any[]>([]),
  endTime: ref(""),
};
const renderData = ref<any[]>([]);
const endTimeList = ref<any[]>([]);
let columns:any = reactive([
  {
    title: '序号',
    dataIndex:'index',
    align: 'center',
    fixed: 'left',
    width: 80,
  },
  {
    title: '部门',
    dataIndex:'departmentName',
    align: 'center',
    fixed: 'left',
    width: 120,
  },
  {
    title: '服务项目',
    dataIndex:'projectName',
    align: 'center',
    width: 120,
  },
]);

let sumData:any = reactive({
  departmentName: '合计',
  projectName: '',
})
const summary = () => {
  return [sumData]
}

const spanMethod = ({rowIndex, columnIndex}) =>{
  if(rowIndex == 0 && columnIndex == 0){
    return {
        colspan: 3
      }
  }
}


function formatNumber(num) {
    let result = num.toFixed(4).replace(/(\.\d*?)0+$/, '$1');
    if (result.endsWith('.')) {
        result = result.slice(0, -1);
    }
    return result;
}

// 修改fetchData函数，直接使用静态数据
const fetchData = async() => {
  let startTime = "";
  let endTime = "";
  if(formModel.dateRange.value!=null && formModel.dateRange.value.length>1){
    startTime = formModel.dateRange.value[0];
    endTime = formModel.dateRange.value[1];
  }

  sumData = {
    departmentName: '合计',
    projectName: '',
  }


  endTimeList.value = [];
  // const [startDate, endDate] = formModel.dateArea.value.map(date => date ? date.format('YYYY-MM-DD') : '');
  let res = await postRequest("/dsms/ihgDataProcess/queryGovernmentStatisticalByProjectName", {
    areaName:formModel.areaName.value,
    startTime: startTime,
    endTime: endTime
  });
 
  let myColumns:any[] = [
  {
    title: '序号',
    dataIndex:'index',
    align: 'center',
    fixed: 'left',
    width: 80,
  },{
    title: '部门',
    dataIndex:'departmentName',
    align: 'center',
    fixed: 'left',
    width: 100,
  },
  {
    title: '服务项目',
    dataIndex:'projectName',
    align: 'center',
    fixed: 'left',
    width: 130,
  }]
  // 计算合计行数据
  res.forEach((item: any,index: number) => {
    if(item.resDataArray!= null && item.resDataArray.length>0){
      item.resDataArray.forEach((item1: any,index1:number) => {
        if(index == 0){
          myColumns.push({
          title: item1.areaName,
          dataIndex: 'city'+index1,
          align: 'center',
          width: 300,
          //所有渠道办理的总办件数	所有渠道办理涉及的总金额（万元）	i黄冈”办理的办件数	i黄冈”办理涉及的金额（万元）

          children:[{
            title: '所有渠道办理的总办件数',
            dataIndex: 'city'+index1+'Sum1',
            sortable: {sortDirections: ['ascend', 'descend']},
            align: 'center',
            width: 150,
          },{
            title: '所有渠道办理涉及的总金额（万元）',
            dataIndex: 'city'+index1+'Sum2',
            sortable: {sortDirections: ['ascend', 'descend']},
            align: 'center',
            width: 150,
          },{
            title: 'i黄冈”办理的办件数',
            dataIndex: 'city'+index1+'Sum3',
            sortable: {sortDirections: ['ascend', 'descend']},
            align: 'center',
            width: 150,
          },{
            title: '“i黄冈”办理涉及的金额（万元）',
            dataIndex: 'city'+index1+'Sum4',
            sortable: {sortDirections: ['ascend', 'descend']},
            align: 'center',
            width: 150,
          }
          ]  
        })
        }
      })
    }
    
    // let socialOrderCountSum = 0;
    // let socialEnterMarketCountSum = 0;
    // let socialOnlineServiceCountSum = 0;
    // let socialInvolveMoneySum = 0;
    item.resDataArray.forEach((item2:any,index2:number)=>{
      endTimeList.value.push(item2.createdTime);
      item['city'+index2+'Sum1'] = item2.governmentAllOrderCountSum;
      item['city'+index2+'Sum2'] = item2.governmentAllOrderMoneySum;
      item['city'+index2+'Sum3'] = item2.governmentIhgOrderCountSum;
      item['city'+index2+'Sum4'] = item2.governmentIhgOrderMoneySum;
      // socialOrderCountSum = socialOrderCountSum + item2.socialOrderCountSum;
      // socialEnterMarketCountSum = socialEnterMarketCountSum + item2.socialEnterMarketCountSum;
      // socialOnlineServiceCountSum = socialOnlineServiceCountSum + item2.socialOnlineServiceCountSum;
      // socialInvolveMoneySum = socialInvolveMoneySum + item2.socialInvolveMoneySum;
    })
    // sumData['city'+index+'Sum1'] = socialOrderCountSum;
    // sumData['city'+index+'Sum2'] = socialEnterMarketCountSum;
    // sumData['city'+index+'Sum3'] = socialOnlineServiceCountSum;
    // sumData['city'+index+'Sum4'] = socialInvolveMoneySum;

    // sumData.governmentIhgOrderCount = sumData.governmentIhgOrderCount + Number(item.governmentIhgOrderCount);
    // sumData.socialInvolveMoneySum = sumData.socialInvolveMoneySum + Number(item.socialInvolveMoneySum);
    // sumData.socialOrderCountSum = sumData.socialOrderCountSum + Number(item.socialOrderCountSum);
    // sumData.socialEnterMarketCountSum = sumData.socialEnterMarketCountSum + Number(item.socialEnterMarketCountSum);
    // sumData.socialOnlineServiceCountSum = sumData.socialOnlineServiceCountSum + Number(item.socialOnlineServiceCountSum);
  });
  columns = formatSortByTitle(myColumns);
  res.forEach((item: any,index:number) => {
    item.index = index+1;
    for (const key in item) {
      if(key  != 'departmentName'){
        if(sumData[key] == null || sumData[key]  == undefined){
          sumData[key]  = 0;
        }
        sumData[key] = sumData[key] + Math.round(1000 * item[key]);
        // sumData[key] = sumData[key] + Number(item[key]);
      }
    }
  })
  
  for (const key in sumData) {
    if(key != 'index' && key != 'departmentName' && key != 'projectName'){
      sumData[key] = sumData[key] / 1000;
    }
  }
  sumData['index'] = '合计';
  // formatNumber();
  for (const key in sumData) {
      if(key  != 'departmentName' && sumData[key] !=null &&  isNumber(sumData[key]) && !isNaN(sumData[key])){
        console.log(sumData[key])
        sumData[key] = formatNumber(sumData[key]);
      }
  }
  console.log(sumData);
  // sumData.socialInvolveMoneySum = sumData.socialInvolveMoneySum.toFixed(5);
  res = formatSortByGov(res);
  res.forEach((item: any,index: number) => {
      item.index = index+1;
  });
  renderData.value = res;
  let timeRes = await postRequest("/dsms/ihgDataProcess/queryGovLastDay", {
    areaName:formModel.areaName.value,
    startTime: startTime,
    endTime: endTime,
    pageSize:1
  });
  console.log(timeRes);
  if(timeRes.list.length>0){
    let latest = timeRes.list[0].createdTime;
    for (let i = 1; i < timeRes.list.length; i++) {
      if (new Date(timeRes.list[i].createdTime) > new Date(latest)) {
        latest = timeRes.list[i].createdTime;
      }
    }
    console.log(timeRes);
    formModel.endTime.value = latest.substring(0,10);
  }
};

fetchData();
</script>

<script lang="ts">
export default {
  name: 'comprehensive',
};
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}
  ::v-deep(.arco-input-wrapper .arco-input[disabled]){
    color: black;
    -webkit-text-fill-color: black;
  }
</style>